package com.cjw.util;

import com.cjw.enums.ErrorCode;
import com.cjw.enums.eventTracking.MatomoApi;
import com.cjw.enums.eventTracking.MatomoApiValue;
import com.cjw.exceptions.BusinessException;
import com.cjw.pojo.entity.DoTest;
import com.cjw.pojo.entity.database.MatomoReponse;
import com.google.gson.Gson;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @create_time:2021.11.24
 * @author : cjw
 * @descripe: Matomo接口调用工具类
 */
public class MatomoHttpClientUtil {

    private static String url = "http://106.15.227.184/?module=API"; // matomo服务器地址

    private static String token = "816bdbbf4e09ff4bb42138a163a62112";// 令牌

    private static String format = "json";//返回格式 默认为json

    /**
     * 带参数的get请求
     * @param
     * @param clazz
     * @return
     */
    public static <T> List<T> doGET(Map<MatomoApi, MatomoApiValue> map, Class<DoTest> clazz) {
        CloseableHttpClient aDefault = HttpClients.createDefault();
        Boolean flag = true;
        // 拼接url
        String resultString = "";
        Iterator<Map.Entry<MatomoApi, MatomoApiValue>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<MatomoApi, MatomoApiValue> next = iterator.next();
            String api = next.getKey().getMsg();
            String value = next.getValue().getMsg();
            url = url + api + "="+value;
        }
        url = url+"&format="+format+"&token_auth="+token;

        // 调用matomo接口
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            URI build = uriBuilder.build();
            HttpGet httpGet = new HttpGet(build);
            CloseableHttpResponse execute = aDefault.execute(httpGet);
            if (execute.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(execute.getEntity(), "UTF-8");
            }
            Gson gson = new Gson();
            // 返回异常处理
            MatomoReponse matomoReponse = null;
            try {
                matomoReponse = gson.fromJson(resultString, MatomoReponse.class);
            } catch (Exception e) {
                flag = false;
            }

            if (flag) {
                if (matomoReponse.getResult() != null && matomoReponse.getResult().equals("error")) {
                    ErrorCode httpError = ErrorCode.HTTP_ERROR;
                    httpError.setMsg(matomoReponse.getMessage());
                    throw new BusinessException(httpError);
                } else if (matomoReponse.getResult() == null) {
                    throw new BusinessException(ErrorCode.CONNECT_ERROR);
                }
            } else {
                List list = gson.fromJson(resultString, List.class);
                List list1 = new ArrayList();
                for (Object o : list) {
                    list1.add(gson.fromJson(gson.toJson(o), clazz));
                }
                return list1;
            }

        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
